package com.zscat.mallplus.sms.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.pms.entity.PmsProduct;
import com.zscat.mallplus.pms.service.IPmsProductService;
import com.zscat.mallplus.sms.entity.SmsPreSale;
import com.zscat.mallplus.sms.service.ISmsPreSaleService;
import com.zscat.mallplus.util.EasyPoiUtils;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;

/**
 * @author mallplus
 * @date 2020-06-30
 * 预售活动
 */
@Slf4j
@RestController
@RequestMapping("/sms/smsPreSale")
public class SmsPreSaleController {

    @Resource
    private ISmsPreSaleService ISmsPreSaleService;
    @Resource
    private IPmsProductService productService;

    @SysLog(MODULE = "sms", REMARK = "根据条件查询所有预售活动列表")
    @ApiOperation("根据条件查询所有预售活动列表")
    @GetMapping(value = "/list")
    @PreAuthorize("hasAuthority('sms:smsPreSale:read')")
    public Object getSmsPreSaleByPage(SmsPreSale entity,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        try {
            return new CommonResult().success(ISmsPreSaleService.page(new Page<SmsPreSale>(pageNum, pageSize), new QueryWrapper<>(entity)));
        } catch (Exception e) {
            log.error("根据条件查询所有预售活动列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "sms", REMARK = "保存预售活动")
    @ApiOperation("保存预售活动")
    @PostMapping(value = "/create")
    @PreAuthorize("hasAuthority('sms:smsPreSale:create')")
    public Object saveSmsPreSale(@RequestBody SmsPreSale entity) {
        try {
            List<PmsProduct> list = entity.getProductList();
            String goodsIs = "";
            BigDecimal originPrice = BigDecimal.ZERO;
            for (PmsProduct p : list) {
                originPrice = originPrice.add(p.getPrice());
                goodsIs = goodsIs + p.getId() + ",";
            }

            entity.setGoodsids(goodsIs.substring(0, goodsIs.length() - 1));
            entity.setCreateTime(new Date());
            if (ISmsPreSaleService.save(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("保存预售活动：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "sms", REMARK = "更新预售活动")
    @ApiOperation("更新预售活动")
    @PostMapping(value = "/update/{id}")
    @PreAuthorize("hasAuthority('sms:smsPreSale:update')")
    public Object updateSmsPreSale(@RequestBody SmsPreSale entity) {
        try {
            List<PmsProduct> list = entity.getProductList();
            String goodsIs = "";
            BigDecimal originPrice = BigDecimal.ZERO;
            for (PmsProduct p : list) {
                originPrice = originPrice.add(p.getPrice());
                goodsIs = goodsIs + p.getId() + ",";
            }

            entity.setGoodsids(goodsIs.substring(0, goodsIs.length() - 1));
            if (ISmsPreSaleService.updateById(entity)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("更新预售活动：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "sms", REMARK = "删除预售活动")
    @ApiOperation("删除预售活动")
    @GetMapping(value = "/delete/{id}")
    @PreAuthorize("hasAuthority('sms:smsPreSale:delete')")
    public Object deleteSmsPreSale(@ApiParam("预售活动id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("预售活动id");
            }
            if (ISmsPreSaleService.removeById(id)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            log.error("删除预售活动：%s", e.getMessage(), e);
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "sms", REMARK = "给预售活动分配预售活动")
    @ApiOperation("查询预售活动明细")
    @GetMapping(value = "/{id}")
    @PreAuthorize("hasAuthority('sms:smsPreSale:read')")
    public Object getSmsPreSaleById(@ApiParam("预售活动id") @PathVariable Long id) {
        try {
            if (ValidatorUtils.empty(id)) {
                return new CommonResult().paramFailed("预售活动id");
            }
            SmsPreSale entity = ISmsPreSaleService.getById(id);
            List<Long> resultList = new ArrayList<>(entity.getGoodsids().split(",").length);
            for (String s : entity.getGoodsids().split(",")) {
                resultList.add(Long.valueOf(s));
            }
            List<PmsProduct> list = productService.list(new QueryWrapper<PmsProduct>().in("id",resultList));
            entity.setProductList(list);
            return new CommonResult().success(entity);
        } catch (Exception e) {
            log.error("查询预售活动明细：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }

    }

    @ApiOperation(value = "批量删除预售活动")
    @RequestMapping(value = "/delete/batch", method = RequestMethod.GET)
    @SysLog(MODULE = "sms", REMARK = "批量删除预售活动")
    @PreAuthorize("hasAuthority('sms:smsPreSale:delete')")
    public Object deleteBatch(@RequestParam("ids") List
            <Long> ids) {
        boolean count = ISmsPreSaleService.removeByIds(ids);
        if (count) {
            return new CommonResult().success(count);
        } else {
            return new CommonResult().failed();
        }
    }


    @SysLog(MODULE = "sms", REMARK = "导出社区数据")
    @GetMapping("/exportExcel")
    public void export(HttpServletResponse response, SmsPreSale entity) {
        // 模拟从数据库获取需要导出的数据
        List<SmsPreSale> personList = ISmsPreSaleService.list(new QueryWrapper<>(entity));
        // 导出操作
        EasyPoiUtils.exportExcel(personList, "导出社区数据", "社区数据", SmsPreSale.class, "导出社区数据.xls", response);

    }

    @SysLog(MODULE = "sms", REMARK = "导入社区数据")
    @PostMapping("/importExcel")
    public void importUsers(@RequestParam MultipartFile file) {
        List<SmsPreSale> personList = EasyPoiUtils.importExcel(file, SmsPreSale.class);
        ISmsPreSaleService.saveBatch(personList);
    }
}


